<?php
//Plugin: OpenID Connect (google account)
//Author: Ivan
//Connect with OpenID

if (!isset($website) ) { header('HTTP/1.1 404 Not Found'); die; }

$PluginEnabled = '0';
//Enable edit plugin options
//$PluginOptions = '1';

if ($PluginEnabled == 1  ) {

    if ( OS_GetAction("google") AND !is_logged() ) {
	include("inc/fb/openid.php");
	AddEvent("os_start","OS_OpenID_Init");
	}
	
	if ( OS_GetAction("google") AND is_logged() ) {  header("location: ".OS_HOME); die;  }
	
	function OS_OpenID_Init() {
	   try {
    $openid = new LightOpenID;
    if(!$openid->mode) {
        if( OS_GetAction("google") AND !is_logged() ) {
            $openid->identity = 'https://www.google.com/accounts/o8/id';
			$openid->required = array('namePerson/first', 'namePerson/last', 'contact/email');
            header('Location: ' . $openid->authUrl());
        }
		
		} elseif($openid->mode == 'cancel') {
          header("location: ".OS_HOME); die;
          } else {
		if($openid->validate())
		{
  $error = "";	
  $identity = $openid->identity;
  $attributes = $openid->getAttributes();
  $email = $attributes['contact/email'];
			
  $first_name = $attributes['namePerson/first'];
  $last_name = $attributes['namePerson/last'];
  $username = $first_name. " " . $last_name;
  $email = $attributes['contact/email'];
  $pass = generate_hash(5);
  $hash = generate_hash(12);
  $password_db = generate_password($pass, $hash); 
  
  if (strlen($username)<=3 ) os_trigger_error( "Username does not have enough characters. Check your google account.");
  
  if ( strlen($email)<=6 ) os_trigger_error( "Invalid Email address. Check your google account.");
  
  global $db;
  
  $result = $db->query("SELECT * FROM ".OSDB_USERS." WHERE LOWER(user_email) = LOWER('".$email."') LIMIT 1");
  $row  = $db->fetch_array($result,'assoc');
  if ( $db->num_rows($result)>=1 ) {
  //Check if user already registered with OpenID
  $result2 = $db->query("SELECT * FROM ".OSDB_CUSTOM_FIELDS." 
  WHERE field_value = '".$email."' AND field_name = 'os_openID' AND field_id = '".$row["user_id"]."' LIMIT 1");
  
  if ( $db->num_rows($result2)>=1 ) {

  $row2 = $db->fetch_array($result2,'assoc');
        $id = $row2["field_id"];
		
  	    $_SESSION["user_id"] = $id ;
	    $_SESSION["username"] =$row["user_name"];
	    $_SESSION["email"]    = $row["user_email"];
	    $_SESSION["level"]    = $row["user_level"];
	    $_SESSION["can_comment"]    = $row["can_comment"];
	    $_SESSION["logged"]    = time();
	    $_SESSION["openID"]    = $id;
		
		$update = $db->query("UPDATE ".OSDB_USERS." SET user_last_login = '".time()."' 
		WHERE user_id = '".$id."' LIMIT 1");
		
	    header("location: ".OS_HOME.""); die;
  
  } else
  os_trigger_error( "Email address ($email) used by another user.");
  
  }
  
  
  $chkun = $db->query("SELECT * FROM ".OSDB_USERS." WHERE LOWER(user_name) = LOWER('".$username."') ");
  if ( $db->num_rows($chkun)>=1 ) $username.=" ".rand(100,1000);
  
    $IP = safeEscape($_SERVER["REMOTE_ADDR"]);
	
  	$insert = $db->query("INSERT INTO ".OSDB_USERS."(user_name, user_password, password_hash, user_email, user_joined, user_level, user_last_login, user_ip) 
	VALUES('".safeEscape($username)."', '".$password_db."', '".$hash."', '".($email)."', '".(int)time()."', '0', '".(int)time()."', '".$IP."')");
	
	$id = $db->get_insert_id();
  
    OS_add_custom_field( $id, 'os_openID' , $email);
  	    $_SESSION["user_id"] = $id ;
	    $_SESSION["username"] =$username;
	    $_SESSION["email"]    = $email;
	    $_SESSION["level"]    = 0;
	    $_SESSION["can_comment"]    = 1;
	    $_SESSION["logged"]    = time();
		$_SESSION["openID"]    = $id ;
		
	    header("location: ".OS_HOME.""); die;
		
        echo "$username | $email | $pass | $identity ".strlen($identity)."<br />";


if (!empty($error) ) {
   os_trigger_error( "An error occurred while registering.");
   }
   else {

    //SUCCESS ! ! //////////////////////////
   }
/*
			echo 'User <b>' . $openid->identity . '</b> has logged in.<br>';
			
			echo "<h3>User information</h3>";
				
			echo "mode: " . $openid->mode . "<br>";
			echo "identity: " . $identity . "<br>";
			echo "email: " . $email . "<br>";
			echo "first_name: " . $first_name . "<br>";
			echo "last_name: " . $last_name . "<br>";
*/		
  }
	else
		{
		     os_trigger_error( "User " . $openid->identity . " has not logged in.");
		}
    }
		
		
	} catch(ErrorException $e) {
	   os_trigger_error( $e->getMessage() );
       }

  }

}
?>